package com.webdev.newtech.controller;

import java.awt.Font;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webdev.newtech.utils.AjaxResult;
import com.webdev.newtech.utils.RedisUtil;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("captcha")
public class CaptchaController {

    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/get")
    public void captcha(String date,HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("验证码--当前用户的sessionID为:"+request.getSession().getId());
        // 设置请求头为输出图片类型
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 三个参数分别为宽、高、位数
        GifCaptcha specCaptcha = new GifCaptcha(130, 38, 5);
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_NUM_AND_UPPER);
        // 验证码存入session
        request.getSession().setAttribute("captcha", specCaptcha.text().toLowerCase());
        System.out.println("真实的验证码是："+specCaptcha.text().toLowerCase());
        // 输出图片流
        specCaptcha.out(response.getOutputStream());
    }

    @PostMapping("/get")
    public AjaxResult getCaptcha(){
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String img = specCaptcha.toBase64(); //base64格式的图片
// 如果不想要base64的头部data:image/png;base64,
//        specCaptcha.toBase64("");  // 加一个空的参数即可
        String answer = specCaptcha.text(); //验证码的答案 -- 一般需要在后台保存，用于校验用户输入的是否正确
        String uuid = UUID.randomUUID().toString(); //生成一个唯一的随机码
        //把答案存到redis缓存数据库
        redisUtil.set(uuid,answer,100);
        //给用户看的，千万别把答案给了
        Map<String,String> map = new HashMap<>();
        map.put("captcha",img);
        map.put("uuid",uuid);
        return  AjaxResult.success(map);
    }
}